from datetime import datetime, timedelta


from jose import JWSError, jwt
from models import User
from config import SECRET_KEY, ALGORITHM, PWD_CONTENT





def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    验证密码
    :param plain_password: 原始密码
    :param hashed_password: 数据库中存储的哈希密码
    :return: 验证是否通过
    """
    try:
        return PWD_CONTENT.verify(plain_password, hashed_password)
    except Exception as e:
        print(f"Password verification error: {str(e)}")
        return False

def authenticate_user(db, username: str, password: str):
    user = db.query(User).filter(User.username == username).first()
    if not user or not verify_password(password, user.password):
        return None
    return user


def reset_user_password(db, username: str, new_password: str):
    """
    重置用户密码并正确哈希
    :param db: 数据库会话
    :param username: 用户名
    :param new_password: 新密码
    :return: 更新后的用户对象或None
    """
    try:
        user = db.query(User).filter(User.username == username).first()
        if user:
            user.set_password(new_password)
            db.save(user)
            return user
        return None
    except Exception as e:
        print(f"Password reset error: {str(e)}")
        return None
    
def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    expire = datetime.now() + (expires_delta or timedelta(minutes=15))
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt